//
//  SSEmoticonInputView.swift
//  表情键盘
//
//  Created by 叶竞泽 on 2017/2/9.
//  Copyright © 2017年 叶竞泽. All rights reserved.
//

import UIKit

/// 表情输入视图
class SSEmoticonInputView: UIView {
    
    // MARK: - 属性
    
    fileprivate let cellIdentifier = "cellIdentifier"

    /// 表情集合视图
    @IBOutlet weak var collectionView: UICollectionView!
    
    /// 工具栏
    @IBOutlet weak var toolbar: SSEmoticonToolbar!
    
    /// 选中表情回调闭包属性
    fileprivate var selectedEmoticonCallback: ((_ emoticon: SSEmoticon?) -> ())?
    
    /// 类方法
    ///
    /// - Returns: 返回表情视图
    class func inputView(selectedEmoticon: @escaping (_ emoticon: SSEmoticon?) -> ()) -> SSEmoticonInputView? {
        
        guard let inputView = UINib(nibName: "SSEmoticonInputView", bundle: nil).instantiate(withOwner: nil, options: nil).first as? SSEmoticonInputView else {
            return nil
        }
        
        inputView.selectedEmoticonCallback = selectedEmoticon
        
        return inputView
    }
    
    // MARK: - 生命周期
    
    override func awakeFromNib() {
        
        collectionView.backgroundColor = UIColor.white
        
        // 注册可重用cell
        collectionView.register(SSEmoticonCell.self, forCellWithReuseIdentifier: cellIdentifier)
        
    }
}

// MARK: - 数据源方法
extension SSEmoticonInputView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        // 页面的数量 = SSEmoticonManager.shared.packages[section].emoticons.count / 20
        return SSEmoticonManager.shared.packages[section].numberOfPages
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? SSEmoticonCell {
            
            // 设置cell页面的表情数组
            cell.emoticons = SSEmoticonManager.shared.packages[indexPath.section].emoticons(page: indexPath.item)
            cell.delegate = self
            return cell
        }
        return UICollectionViewCell()
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return SSEmoticonManager.shared.packages.count
    }

}

extension SSEmoticonInputView: SSEmoticonCellDelegate {
    
    func emoticonCellDidSelectedEmoticon(cell: SSEmoticonCell, emoticon: SSEmoticon?) {
      
        // 执行闭包
        selectedEmoticonCallback?(emoticon)
    }
}
